package com.springcloud.sc.ucpv5.client.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public class DataFileUtil {

	/**
	 * 从文件加载对象
	 * 
	 * @param fileName
	 * @return
	 */
	public static Object loadFromFile(String fileName) {
		if (null == fileName) {
			return null;
		}

		File file = new File(fileName);
		if (!file.exists()) {
			return null;
		}

		FileInputStream stream = null;
		ObjectInputStream in = null;
		try {
			stream = new FileInputStream(file);

			in = new ObjectInputStream(stream);
			return in.readObject();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != in) {
					in.close();
				}
			} catch (IOException e) {

			}
		}

		return null;
	}

	/**
	 * 保存序列号对象到文件中
	 * 
	 * @param fileName
	 * @param saveObj
	 */
	public static void saveToFile(String fileName, Object saveObj) {
		if (null == fileName || null == saveObj) {
			return;
		}

		FileOutputStream outputStream = null;
		ObjectOutputStream out = null;

		try {
			File file = new File(fileName);
			if (!file.exists()) {
				if (file.getParentFile() != null) {
					file.getParentFile().mkdirs();
				}
				file.createNewFile();
			} else if (!file.canWrite()) {
				file.delete();
				file.createNewFile();
			}
			outputStream = new FileOutputStream(file);
			out = new ObjectOutputStream(outputStream);
			out.writeObject(saveObj);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != out) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 获取路径下的所有文件/文件夹
	 * 
	 * @param directoryPath
	 *            需要遍历的文件夹路径
	 * @param isAddDirectory
	 *            是否将子文件夹的路径也添加到list集合中
	 * @return
	 */
	public static List<File> getAllFile(String directoryPath) {
		List<File> list = new ArrayList<File>();
		File baseFile = new File(directoryPath);
		if (baseFile.isFile() || !baseFile.exists()) {
			return list;
		}
		File[] files = baseFile.listFiles();
		for (File file : files) {
			if (file.isDirectory()) {
				list.addAll(getAllFile(file.getAbsolutePath()));
			} else {
				list.add(file);
			}
		}
		return list;
	}
}
